﻿using FileAssistant.ZModel;
using FileAssistant.ZStatic;
using FileAssistant.ZTool;
using Microsoft.WindowsAPICodePack.Dialogs;
using MS.WindowsAPICodePack.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FileAssistant
{
    
    public partial class MainWindow : Window
    {

        private RepeatResult rr = new RepeatResult();

        public MainWindow()
        {
            InitializeComponent();
            //zpath.Text = label3.ActualWidth.ToString();
        }

        //浏览按钮
        private void Button_FolderChose(object sender, RoutedEventArgs e)
        {
            var dialog = new CommonOpenFileDialog();
            dialog.Title = "请选择文件路径";
            dialog.IsFolderPicker = true;
            if(dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                zpath.Text = dialog.FileName;
            }
        }

        //信息按钮
        private void Info_OnMouseDown(object sender,MouseButtonEventArgs e)
        {
            if(e.ChangedButton == MouseButton.Left && e.ClickCount == 1)
            {
                XiaoChenSoftIntro xci = new XiaoChenSoftIntro();
                xci.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                xci.Owner = this;
                xci.Show();
            }
        }

        //主页按钮
        private void Home_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && e.ClickCount == 1)
            {
                var ct = zpath.Text;

                MessageBox.Show("你点击了主页按钮");
                e.Handled = true;
            }
        }

        private async void Zpath_TextChanged(object sender, TextChangedEventArgs e)
        {
            var pathName = zpath.Text;
            if (Directory.Exists(pathName))
            {
                var strTemp = new StringBuilder(logArea.Text);

                //每次打印完了自己加上换行
                strTemp.Append("文件路径: " + "\"" + pathName + "\"" + " 存在");
                strTemp.Append("    " + DateTime.Now);
                strTemp.Append("\n");

                //然后打印文件夹下的文件名
                var fct = new FileControlTool();
                var alist = new List<string>();

                await Task.Run(() => {
                    alist = fct.GetFileNamesOfOneDir(pathName);
                });

                for (int i = 0; i < alist.Count; i++)
                {
                    strTemp.Append(alist[i] + "\n");
                }

                logArea.Text = strTemp.ToString();
            }
        }

        private async Task Button_Replace(object sender, RoutedEventArgs e)
        {
            replace.IsEnabled = false;
            restore.IsEnabled = false;
            //var result = new RepeatResult();

            try
            {
                var azpath = zpath.Text;
                var abeReplaceContent = beReplaceContent.Text;
                var aNumberN = NumberN.Text;
                var afileType = fileType.Text;
                var anewContent = newContent.Text;
                var arepeatCount = repeatCount.Text;

                var fct = new FileControlTool();

                //输入检查
                var tcr = fct.ConditionCheck(azpath, abeReplaceContent, aNumberN, afileType, anewContent, arepeatCount);
                logArea.Text += tcr.ResultDescription;

                //如果通过检查，继续进行下一步
                if (tcr.Pass)
                {
                    //拿到目录下所有文件
                    var alist = fct.GetFileNamesOfOneDir(tcr.TargetPath);


                    await Task.Run(() =>
                    {
                        for (int i = 0; i < alist.Count; i++)
                        {
                            var newTemp = tcr.NewContent;

                            var fullName = alist[i];
                            var splitArr1 = fullName.Split('\\');
                            var splitArr2 = fullName.Split('.');
                            var shortName = splitArr1[splitArr1.Length - 1];
                            var shortNameTemp = shortName;
                            var fileType = splitArr2[splitArr2.Length - 1];

                            if (alist.Count > 0 && i == 0)
                            {
                                rr.Prefix = fullName.Substring(0, fullName.Length - shortNameTemp.Length);
                            }

                            if (afileType != "")
                            {
                                if (fileType == afileType)
                                {
                                    //准备新内容
                                    if (tcr.RepeatCount > 0)
                                    {
                                        for (int j = 0; j < tcr.RepeatCount - 1; j++)
                                        {
                                            newTemp += newTemp;
                                        }
                                    }


                                    //根据次序是否设置，选择不同的替换方法
                                    if (tcr.No == 0)
                                    {
                                        //MessageBox.Show(shortName +"\n"+ tcr.OldContent);
                                        //Console.WriteLine(tcr.OldContent);
                                        shortName = shortName.Replace(tcr.OldContent, newTemp);
                                    }
                                    else
                                    {
                                        shortName = fct.CreatNewFileName(shortName, tcr.OldContent, tcr.No, newTemp);
                                    }

                                    if (shortName != shortNameTemp)
                                    {
                                        rr.Count++;
                                        rr.BeforeChange.Add(shortNameTemp);
                                        rr.AfterChange.Add(shortName);

                                        //执行替换
                                        File.Move(fullName, fullName.Replace(System.IO.Path.GetFileName(fullName), shortName));
                                    }

                                }
                            }
                            else
                            {
                                //准备新内容
                                if (tcr.RepeatCount > 1)
                                {
                                    for (int j = 0; j < tcr.RepeatCount - 1; j++)
                                    {
                                        tcr.NewContent += tcr.NewContent;
                                    }
                                }
                                else
                                {
                                    tcr.NewContent += tcr.NewContent;
                                }

                                //根据次序是否设置，选择不同的替换方法
                                if (tcr.No == 0)
                                {
                                    //MessageBox.Show(shortName +"\n"+ tcr.OldContent);
                                    //Console.WriteLine(tcr.OldContent);
                                    shortName = shortName.Replace(tcr.OldContent, tcr.NewContent);
                                }
                                else
                                {
                                    shortName = fct.CreatNewFileName(shortName, tcr.OldContent, tcr.No, tcr.NewContent);
                                }

                                if (shortName != shortNameTemp)
                                {
                                    rr.Count++;
                                    rr.BeforeChange.Add(shortNameTemp);
                                    rr.AfterChange.Add(shortName);

                                    //执行替换
                                    File.Move(fullName, fullName.Substring(0, fullName.Length - shortNameTemp.Length) + shortName);

                                    //rr = result;
                                }
                            }

                        }
                    });
                    

                    if (rr.Count > 0)
                    {
                        var strTemp = new StringBuilder(logArea.Text);
                        strTemp.Append($"共{rr.Count}文件名发生变化，具体如下所示：\n");
                        for (int i = 0; i < rr.Count; i++)
                        {
                            strTemp.Append(rr.BeforeChange[i] + " => " + rr.AfterChange[i] + " \n");
                        }
                        logArea.Text = strTemp.ToString();
                    }
                    MessageBox.Show("执行完成，共" + rr.Count + "项发生变化");
                }
                else
                {
                    MessageBox.Show("条件检查未通过，请根据检查结果修改后重试");
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show($"出错：{ex.Message}");
            }
            finally
            {
                replace.IsEnabled = true;
                restore.IsEnabled = true;
            }

            

            //StaticOne.ZStatic_RepeatResult = result;
        }

        private void LogArea_TextChanged(object sender, TextChangedEventArgs e)
        {
            logArea.ScrollToEnd();
        }

        //还原操作
        private async Task Button_Restore(object sender, RoutedEventArgs e)
        {

            replace.IsEnabled = false;
            restore.IsEnabled = false;

            try
            {
                if (rr.Count > 0)
                {
                    await Task.Run(() =>
                    {
                        for (int i = 0; i < rr.Count; i++)
                        {
                            //执行还原
                            File.Move(rr.Prefix + rr.AfterChange[i], rr.Prefix + rr.BeforeChange[i]);
                        }

                        //记录对调
                        var Beforetemp = new List<string>();
                        for (int i = 0; i < rr.Count; i++)
                        {
                            Beforetemp.Add(rr.BeforeChange[i]);
                            rr.BeforeChange[i] = rr.AfterChange[i];
                            rr.AfterChange[i] = Beforetemp[i];
                        }
                    });

                    var strTemp = new StringBuilder(logArea.Text);
                    //打印还原记录
                    strTemp.Append($"共{rr.Count}文件名完成还原，具体如下所示：\n");
                    for (int i = 0; i < rr.Count; i++)
                    {
                        strTemp.Append(rr.BeforeChange[i] + " => " + rr.AfterChange[i] + " \n");
                    }
                    logArea.Text = strTemp.ToString();
                }
                else
                {
                    MessageBox.Show("没有可还原的操作");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"出错：{ex.Message}");
            }
            finally
            {
                replace.IsEnabled = true;
                restore.IsEnabled = true;
            }

            
        }

        private async void replace_Click(object sender, RoutedEventArgs e)
        {
            replace.IsEnabled = false;
            restore.IsEnabled = false;
            //var result = new RepeatResult();

            rr.Count = 0;
            rr.BeforeChange.Clear();
            rr.AfterChange.Clear();

            try
            {
                var azpath = zpath.Text;
                var abeReplaceContent = beReplaceContent.Text;
                var aNumberN = NumberN.Text;
                var afileType = fileType.Text;
                var anewContent = newContent.Text;
                var arepeatCount = repeatCount.Text;

                var fct = new FileControlTool();

                //输入检查
                var tcr = fct.ConditionCheck(azpath, abeReplaceContent, aNumberN, afileType, anewContent, arepeatCount);
                logArea.Text += tcr.ResultDescription;

                //如果通过检查，继续进行下一步
                if (tcr.Pass)
                {
                    //拿到目录下所有文件
                    var alist = fct.GetFileNamesOfOneDir(tcr.TargetPath);


                    await Task.Run(() =>
                    {
                        for (int i = 0; i < alist.Count; i++)
                        {
                            var newTemp = tcr.NewContent;

                            var fullName = alist[i];
                            var splitArr1 = fullName.Split('\\');
                            var splitArr2 = fullName.Split('.');
                            var shortName = splitArr1[splitArr1.Length - 1];
                            var shortNameTemp = shortName;
                            var fileType = splitArr2[splitArr2.Length - 1];

                            if (alist.Count > 0 && i == 0)
                            {
                                rr.Prefix = fullName.Substring(0, fullName.Length - shortNameTemp.Length);
                            }

                            if (afileType != "")
                            {
                                if (fileType == afileType)
                                {
                                    //准备新内容
                                    if (tcr.RepeatCount > 0)
                                    {
                                        for (int j = 0; j < tcr.RepeatCount - 1; j++)
                                        {
                                            newTemp += newTemp;
                                        }
                                    }


                                    //根据次序是否设置，选择不同的替换方法
                                    if (tcr.No == 0)
                                    {
                                        //MessageBox.Show(shortName +"\n"+ tcr.OldContent);
                                        //Console.WriteLine(tcr.OldContent);
                                        shortName = shortName.Replace(tcr.OldContent, newTemp);
                                    }
                                    else
                                    {
                                        shortName = fct.CreatNewFileName(shortName, tcr.OldContent, tcr.No, newTemp);
                                    }

                                    if (shortName != shortNameTemp)
                                    {
                                        rr.Count++;
                                        rr.BeforeChange.Add(shortNameTemp);
                                        rr.AfterChange.Add(shortName);

                                        //执行替换
                                        File.Move(fullName, fullName.Replace(System.IO.Path.GetFileName(fullName), shortName));
                                    }

                                }
                            }
                            else
                            {
                                //准备新内容
                                if (tcr.RepeatCount > 1)
                                {
                                    for (int j = 0; j < tcr.RepeatCount - 1; j++)
                                    {
                                        tcr.NewContent += tcr.NewContent;
                                    }
                                }
                                else
                                {
                                    tcr.NewContent += tcr.NewContent;
                                }

                                //根据次序是否设置，选择不同的替换方法
                                if (tcr.No == 0)
                                {
                                    //MessageBox.Show(shortName +"\n"+ tcr.OldContent);
                                    //Console.WriteLine(tcr.OldContent);
                                    shortName = shortName.Replace(tcr.OldContent, tcr.NewContent);
                                }
                                else
                                {
                                    shortName = fct.CreatNewFileName(shortName, tcr.OldContent, tcr.No, tcr.NewContent);
                                }

                                if (shortName != shortNameTemp)
                                {
                                    rr.Count++;
                                    rr.BeforeChange.Add(shortNameTemp);
                                    rr.AfterChange.Add(shortName);

                                    //执行替换
                                    File.Move(fullName, fullName.Substring(0, fullName.Length - shortNameTemp.Length) + shortName);

                                    //rr = result;
                                }
                            }

                        }
                    });


                    if (rr.Count > 0)
                    {
                        var strTemp = new StringBuilder(logArea.Text);
                        strTemp.Append($"共{rr.Count}文件名发生变化，具体如下所示：\n");
                        for (int i = 0; i < rr.Count; i++)
                        {
                            strTemp.Append(rr.BeforeChange[i] + " => " + rr.AfterChange[i] + " \n");
                        }
                        logArea.Text = strTemp.ToString();
                    }
                    MessageBox.Show("执行完成，共" + rr.Count + "项发生变化");
                }
                else
                {
                    MessageBox.Show("条件检查未通过，请根据检查结果修改后重试");
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show($"出错：{ex.Message}");
            }
            finally
            {
                replace.IsEnabled = true;
                restore.IsEnabled = true;
            }

        }

        private async void restore_Click(object sender, RoutedEventArgs e)
        {
            replace.IsEnabled = false;
            restore.IsEnabled = false;

            try
            {
                if (rr.Count > 0)
                {
                    await Task.Run(() =>
                    {
                        for (int i = 0; i < rr.Count; i++)
                        {
                            //执行还原
                            File.Move(rr.Prefix + rr.AfterChange[i], rr.Prefix + rr.BeforeChange[i]);
                        }

                        //记录对调
                        var Beforetemp = new List<string>();
                        for (int i = 0; i < rr.Count; i++)
                        {
                            Beforetemp.Add(rr.BeforeChange[i]);
                            rr.BeforeChange[i] = rr.AfterChange[i];
                            rr.AfterChange[i] = Beforetemp[i];
                        }
                    });

                    var strTemp = new StringBuilder(logArea.Text);
                    //打印还原记录
                    strTemp.Append($"共{rr.Count}文件名完成还原，具体如下所示：\n");
                    for (int i = 0; i < rr.Count; i++)
                    {
                        strTemp.Append(rr.BeforeChange[i] + " => " + rr.AfterChange[i] + " \n");
                    }
                    logArea.Text = strTemp.ToString();
                }
                else
                {
                    MessageBox.Show("没有可还原的操作");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"出错：{ex.Message}");
            }
            finally
            {
                replace.IsEnabled = true;
                restore.IsEnabled = true;
            }
        }
    }
}
